package com.ddwl.user.service;

import com.ddwl.common.constant.*;
import com.ddwl.schema.bo.user.IdentityCardQueryBo;
import com.ddwl.schema.bo.user.IdentityCardRejectBo;
import com.ddwl.schema.bo.user.IdentitySubmitBo;
import com.ddwl.schema.vo.user.IdentityCardVo;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.GateApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.gate.DingTalkBo;
import com.ddwl.schema.bo.gate.PushWxMsgBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.user.dao.UserDao;
import com.ddwl.user.dao.model.User;
import com.ddwl.user.dao.IdentityCardDao;
import com.ddwl.user.dao.UserStatusDao;
import com.ddwl.user.dao.model.IdentityCard;
import com.ddwl.user.dao.model.UserStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类ProfitServer.java的实现描述：推广申请服务
 *
 * @author zach
 * @Date :2020-06-23 11:06.
 */
@Service
public class IdentityCardServer {

    @Resource
    private IdentityCardDao identityCardDao;
    @Resource
    private UserDao userDao;

    @Resource
    private GateApi gateApi;

    @Resource
    private UserStatusDao userStatusDao;

    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询审批通过的用户
     *
     * @return
     */
    public List<IdentityCardVo> querySuccessfulApply() {
        return BeanConverUtils.convertBeanList(identityCardDao.queryApply(), IdentityCardVo.class);
    }

    /**
     * 身份认证提交审批
     *
     * @param identitySubmitBo
     */
    @Transactional(rollbackFor = Exception.class)
    public void submitProfitApply(IdentitySubmitBo identitySubmitBo) {
        ParamException.isFalse(IdcardUtil.isValidCard(identitySubmitBo.getIdCard()), "请输入正确身份证号");
        ParamException.isNull(gateApi.geoRegion(identitySubmitBo.getRegionId()).getResult(), "请输入正确的地址");
        IdentityCard identityCard = BeanConverUtils.convertBean(identitySubmitBo, IdentityCard.class);
        IdentityCard apply = identityCardDao.queryUserApply(identitySubmitBo.getUserId());
        IdentityCard idCard = identityCardDao.queryUserApplyByIdCardAndSucceedStatus(identitySubmitBo.getIdCard());
        identityCard.setStatus(BaseEnum.ApplyEnum.PRE.getCode());
        if (apply != null) {
            ParamException.isTrue(BaseEnum.ApplyEnum.SUCCEED.getCode().equals(apply.getStatus()), "已经审批通过了请勿重复提交");
            ParamException.isTrue(BaseEnum.ApplyEnum.PRE.getCode().equals(apply.getStatus()), "正在审批中请勿重复提交");
            if (!apply.getIdCard().equals(identitySubmitBo.getIdCard())) {
                ParamException.isFalse(identitySubmitBo.getIdCard().equals(idCard.getIdCard()), "该身份证已经审批通过了请勿重复提交");
            }
            identityCard.setId(apply.getId());
            identityCardDao.updateByPrimaryKeySelective(identityCard);
        } else {
            ParamException.isNotNull(idCard, "该身份证已经审批通过了请勿重复提交");
            identityCardDao.insert(identityCard);
            UserStatus userStatus = new UserStatus();
            userStatus.setUserId(identitySubmitBo.getUserId());
            UserStatus us = userStatusDao.selectOne(userStatus);
            //同步用户身份认证状态
            if (us != null) {
                us.setIdcardStatus(UserEnum.UserStatus.PRE.getCode());
                userStatusDao.updateIdCardById(us);
            } else {
                userStatus.setIdcardStatus(UserEnum.UserStatus.PRE.getCode());
                userStatus.setWxStatus(UserEnum.UserStatus.NUL.getCode());
                userStatus.setBankcardStatus(UserEnum.UserStatus.NUL.getCode() );
                userStatusDao.insert(userStatus);
            }
            User user=new User();
            user.setId(identitySubmitBo.getUserId());
            user.setRealname(identitySubmitBo.getIdName());
            user.setBirthday( identitySubmitBo.getIdCard().substring(6,14));
            userDao.updateNameAndBir(user);
        }

        //发送钉钉消息
        DingTalkBo bo1=new DingTalkBo();
        bo1.setMessage("");
        bo1.setChannel(StatisticsEnum.channel.UN_APPROVE_IDCARD.getId());
        rabbitTemplate.convertAndSend(RabbitMqConstants.DINGDING_TALK_MESSAGE, JSON.toJSONString(bo1));
    }

    /**
     * 店铺生成身份认证
     *
     * @param identitySubmitBo
     */
    @Transactional(rollbackFor = Exception.class)
    public void submitfenxiaoProfit(IdentitySubmitBo identitySubmitBo) {
        IdentityCard identityCard = BeanConverUtils.convertBean(identitySubmitBo, IdentityCard.class);
        IdentityCard apply = identityCardDao.queryUserApply(identitySubmitBo.getUserId());
        IdentityCard idCard = identityCardDao.queryUserApplyByIdCardAndSucceedStatus(identitySubmitBo.getIdCard());
        identityCard.setStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
        if (apply != null) {
            ParamException.isTrue(BaseEnum.ApplyEnum.SUCCEED.getCode().equals(apply.getStatus()), "已经审批通过了请勿重复提交");
            ParamException.isTrue(BaseEnum.ApplyEnum.PRE.getCode().equals(apply.getStatus()), "正在审批中请勿重复提交");
            if (!apply.getIdCard().equals(identitySubmitBo.getIdCard())) {
                ParamException.isFalse(identitySubmitBo.getIdCard().equals(idCard.getIdCard()), "该身份证已经审批通过了请勿重复提交");
            }
            identityCard.setId(apply.getId());
            identityCardDao.updateByPrimaryKeySelective(identityCard);
        } else {
            ParamException.isNotNull(idCard, "该身份证已经审批通过了请勿重复提交");
            identityCardDao.insert(identityCard);
            UserStatus userStatus = new UserStatus();
            userStatus.setUserId(identitySubmitBo.getUserId());
            UserStatus us = userStatusDao.selectOne(userStatus);
            //同步用户身份认证状态
            if (us != null) {
                us.setIdcardStatus(UserEnum.UserStatus.SUCCEED.getCode());
                userStatusDao.updateIdCardById(us);
            } else {
                userStatus.setIdcardStatus(UserEnum.UserStatus.SUCCEED.getCode());
                userStatus.setWxStatus(UserEnum.UserStatus.SUCCEED.getCode());
                userStatus.setBankcardStatus(UserEnum.UserStatus.SUCCEED.getCode() );
                userStatusDao.insert(userStatus);
            }
            User user=new User();
            user.setId(identitySubmitBo.getUserId());
            user.setRealname(identitySubmitBo.getIdName());
            user.setBirthday( identitySubmitBo.getIdCard().substring(6,14));
            userDao.updateNameAndBir(user);
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void approveApply(String applyId) {
        IdentityCard apply = identityCardDao.selectByPrimaryKey(applyId);
        ParamException.isNull(apply);
        IdentityCard succeedIdCard=identityCardDao.queryUserApplyByIdCardAndSucceedStatus(apply.getIdCard());
        if(succeedIdCard!=null){
            throw new CommonException("该身份证已经审核通过，请勿重复提交！");
        }else {
        apply.setStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
        identityCardDao.updateByPrimaryKeySelective(apply);
        //userService.updateProfitLevel(apply.getUserId(), UserEnum.ProfitLevelEnum.ZONE.getLevel());
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(applyId);
        userStatus.setIdcardStatus(UserEnum.UserStatus.SUCCEED.getCode());
        userStatusDao.updateIdCardByUserId(userStatus);
        User user = new User();
        user.setId(apply.getUserId());
        user.setRealname(apply.getIdName());
        userDao.updateByPrimaryKeySelective(user);
        //((IdentityCardServer) AopContext.currentProxy()).wxNotify(apply);
        }
    }

    @Async
    public void wxNotify(IdentityCard apply) {
        //微信通知发送接口
        PushWxMsgBo pushWxMsgBo = new PushWxMsgBo();
        pushWxMsgBo.setUserId(apply.getUserId());
        Map<String, String> templateDate = new HashMap<>();
        pushWxMsgBo.setTemplateNum(WxEnum.WxMsgTemplate.TEMPLATEID3.getCode());
        templateDate.put(WxEnum.TEMPLATEINVOKE3.IDNAME.getCode(), apply.getIdName());
        templateDate.put(WxEnum.TEMPLATEINVOKE3.APPLYRESULT.getCode(), BaseEnum.ApplyEnum.SUCCEED.getName());
        templateDate.put(WxEnum.TEMPLATEINVOKE3.APPLYTIME.getCode(), DateUtil.formatDate(apply.getGmtModified(), DateUtil.DATE_TIME_FORMAT3));
        templateDate.put(WxEnum.TEMPLATEINVOKE3.APPLYSUB.getCode(), "恭喜您，您的审核已通过！");
        pushWxMsgBo.setTemplateDate(templateDate);
    }

    /**
     * 拒绝审批
     *
     * @param identityCardRejectBo
     */
    public void rejectApply(IdentityCardRejectBo identityCardRejectBo) {
        IdentityCard identityCard = new IdentityCard();
        identityCard.setId(identityCardRejectBo.getApplyId());
        identityCard.setStatus(BaseEnum.ApplyEnum.FILL.getCode());
        if (StringUtils.hasText(identityCardRejectBo.getRejectReason())) {
            identityCard.setRejectReason(identityCardRejectBo.getRejectReason());
        }
        identityCardDao.updateByPrimaryKeySelective(identityCard);
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(identityCardRejectBo.getApplyId());
        userStatus.setIdcardStatus(UserEnum.UserStatus.FILL.getCode());
        userStatusDao.updateIdCardByUserId(userStatus);

    }

    public IdentityCardVo get(String applyId) {
        return BeanConverUtils.convertBean(identityCardDao.selectByPrimaryKey(applyId), IdentityCardVo.class);
    }


    /**
     * 解除用户身份绑定信息
     *
     * @param applyId
     */
    public void delete(String applyId) {
        identityCardDao.deleteByUserId(applyId);
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(applyId);
        userStatus.setIdcardStatus(UserEnum.UserStatus.NUL.getCode());
        userStatusDao.updateIdCardByUserId(userStatus);
    }

    @Transactional(rollbackFor = Exception.class)
    public IdentityCardVo getUserApply(String userId) {
        return BeanConverUtils.convertBean(identityCardDao.queryUserApply(userId), IdentityCardVo.class);
    }

    public PageVo<IdentityCardVo> page(PageBo<IdentityCardQueryBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), pageBo.isAsc()));
        PageInfo<IdentityCard> info = new PageInfo(identityCardDao.queryApplyList(pageBo.getParam()));
        List<IdentityCardVo> list = BeanConverUtils.convertBeanList(info.getList(), IdentityCardVo.class);
        return new PageVo<>(info.getTotal(), pageBo.getPage(), pageBo.getPageSize(), list);
    }

    public List<IdentityCardVo> getIdCardByCodeAndUserId(String code,String userId) {
        return BeanConverUtils.convertBeanList(identityCardDao.getIdCardByCodeAndUserId(code,userId),IdentityCardVo.class);
    }

    public List<IdentityCardVo> getIdCardByCode(String code) {
        IdentityCard identityCard=new IdentityCard();
        identityCard.setStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
        identityCard.setIdCard(code);
        List<IdentityCardVo> list = BeanConverUtils.convertBeanList(identityCardDao.select(identityCard), IdentityCardVo.class);
        return list;
    }
    public IdentityCardVo getIdCardByUserId(String userId) {
        IdentityCard identityCard=new IdentityCard();
        identityCard.setStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
        identityCard.setUserId(userId);
        IdentityCardVo list = BeanConverUtils.convertBean(identityCardDao.selectOne(identityCard), IdentityCardVo.class);
        return list;
    }

    public IdentityCardVo getIdCardByTel(String tel) {
        IdentityCard identityCard=new IdentityCard();
        identityCard.setStatus(BaseEnum.ApplyEnum.SUCCEED.getCode());
        identityCard.setPhone(tel);
        IdentityCardVo list = BeanConverUtils.convertBean(identityCardDao.selectOne(identityCard), IdentityCardVo.class);
        return list;
    }

    public void changeId() {
        List<IdentityCard> list=identityCardDao.getAll();
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, String> map = new HashMap<>();
            for (IdentityCard ic : list) {
                String id = ic.getId();
                if (id.length() == 11) {
                    long longId = UUIDGenerator.reverseShortUUID(id);
                    map.put(id, String.valueOf(longId));
                }
            }
            if (!CollectionUtils.isEmpty(map)) {
                identityCardDao.changeId(map);
            }
        }
    }
}
